package com.wuming.common.dao;

import com.wuming.common.model.User;
import com.wuming.common.util.JDBCUtil;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 用户DAO
 *
 * @author 童天宇
 */
public class UserDAO {
    /**
     * 根据id查询用户
     *
     * @param id 用户id
     * @return 用户对象
     */
    public static User getUserById(int id) {
        try {
            String sql = "select * from users where id = ?";
            Object[] params = {id};
            ResultSet rs = JDBCUtil.executeQuery(sql, params);
            if (rs.next()) {
                return new User(
                        rs.getInt("id"),
                        rs.getString("phone"),
                        rs.getString("username"),
                        rs.getString("password_hash"),
                        rs.getDate("birthday"),
                        rs.getInt("gender"),
                        rs.getInt("role")
                );
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加用户
     * <p>注意用户对象passwordHash字段需要加密后的字符串!</p>
     *
     * @param user 用户对象
     * @return 添加成功返回true，否则返回false
     */
    public static boolean addUser(User user) {
        String sql = "insert into users (phone, username, password_hash, birthday, gender, role) values (?, ?, ?, ?, ?, ?)";
        Object[] params = {user.getPhone(), user.getUsername(), user.getPasswordHash(), user.getBirthday(), user.getGender(), user.getRole()};
        int count = JDBCUtil.executeUpdate(sql, params);
        return count > 0;
    }

    // 根据需求进行增添
}
